package com.imddy.springmvcuploadftp.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imddy.springmvcuploadftp.service.PictureService;

@RestController
public class PictureController {
	
	private static Log log = LogFactory.getLog(PictureController.class);
	
	@Autowired
	private PictureService pictureService;
	
	// upload是pictureUpload 本地上传到FTP服务器的测试url
	// kindeditor需要produces={"application/json;charset=UTF-8"}，不然返回的json是ISO-8859-1,不是UTF8,不然就去改
	// @RequestMapping(value="pic/upload", produces={"application/json;charset=UTF-8"})
	@RequestMapping(value="pic/upload")
	public String pictureUpload(@RequestParam(value = "fileUpload") MultipartFile uploadFile) {
		String json = "";
		try {
			Map result = pictureService.uploadPicture(uploadFile);
			// 浏览器擅长处理json格式的字符串，为了减少因为浏览器内核不同导致的bug，建议用json
			json = new ObjectMapper().writeValueAsString(result);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return json;
	}
	
	// upload2是uploadPictureForLocal 本地上传到本服务器的测试url
	// kindeditor需要produces={"application/json;charset=UTF-8"}，不然返回的json是ISO-8859-1,不是UTF8
	// @RequestMapping(value="pic/upload2", produces={"application/json;charset=UTF-8"})
	@RequestMapping(value="pic/upload2")
	public String pictureUpload2(@RequestParam(value = "fileUpload") MultipartFile uploadFile, HttpServletRequest request) {
		String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";	
		String json = "";
		try {
			Map result = pictureService.uploadPictureForLocal(filePath,uploadFile);
			// 浏览器擅长处理json格式的字符串，为了减少因为浏览器内核不同导致的bug，建议用json
			json = new ObjectMapper().writeValueAsString(result);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return json;
	}

}
